using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Windows.Input;
using WPF_MVVM_Test.MVVM_Model;
using WPF_MVVM_Test.Services;
using Newtonsoft.Json;
using System.Windows;

namespace WPF_MVVM_Test.MVVM_ViewModel.LMZWorkSchedule
{
    public class InspectionRecordsViewModel : INotifyPropertyChanged
    {
        private readonly ApiService _apiService;
        private ObservableCollection<InspectionRecord> _inspectionRecords;
        private string _orderNameFilter;
        private int _currentPage = 1;
        private int _pageSize = 10;
        private int _totalPages;
        private int _totalRecords;
        private bool _isLoading;

        public InspectionRecordsViewModel()
        {
            _apiService = new ApiService();
            InspectionRecords = new ObservableCollection<InspectionRecord>();
            _orderNameFilter = string.Empty;
            
            // 初始化命令
            SearchCommand = new RelayCommand(async () => await SearchAsync());
            ResetCommand = new RelayCommand(async () => await ResetAsync());
            FirstPageCommand = new RelayCommand(async () => await GoToFirstPageAsync(), () => CurrentPage > 1);
            PreviousPageCommand = new RelayCommand(async () => await GoToPreviousPageAsync(), () => CurrentPage > 1);
            NextPageCommand = new RelayCommand(async () => await GoToNextPageAsync(), () => CurrentPage < TotalPages);
            LastPageCommand = new RelayCommand(async () => await GoToLastPageAsync(), () => CurrentPage < TotalPages);

            // 延迟加载初始数据，避免构造函数中的异步调用问题
            System.Windows.Threading.Dispatcher.CurrentDispatcher.BeginInvoke(
                new System.Action(async () => await LoadDataAsync()),
                System.Windows.Threading.DispatcherPriority.Loaded);
        }

        public ObservableCollection<InspectionRecord> InspectionRecords
        {
            get => _inspectionRecords;
            set
            {
                _inspectionRecords = value;
                OnPropertyChanged(nameof(InspectionRecords));
            }
        }

        public string OrderNameFilter
        {
            get => _orderNameFilter;
            set
            {
                _orderNameFilter = value;
                OnPropertyChanged(nameof(OrderNameFilter));
            }
        }

        public int CurrentPage
        {
            get => _currentPage;
            set
            {
                _currentPage = value;
                OnPropertyChanged(nameof(CurrentPage));
                UpdateCommandStates();
            }
        }

        public int PageSize
        {
            get => _pageSize;
            set
            {
                _pageSize = value;
                OnPropertyChanged(nameof(PageSize));
                _ = LoadDataAsync();
            }
        }

        public int TotalPages
        {
            get => _totalPages;
            set
            {
                _totalPages = value;
                OnPropertyChanged(nameof(TotalPages));
                UpdateCommandStates();
            }
        }

        public int TotalRecords
        {
            get => _totalRecords;
            set
            {
                _totalRecords = value;
                OnPropertyChanged(nameof(TotalRecords));
            }
        }

        public bool IsLoading
        {
            get => _isLoading;
            set
            {
                _isLoading = value;
                OnPropertyChanged(nameof(IsLoading));
            }
        }

        public ICommand SearchCommand { get; }
        public ICommand ResetCommand { get; }
        public ICommand FirstPageCommand { get; }
        public ICommand PreviousPageCommand { get; }
        public ICommand NextPageCommand { get; }
        public ICommand LastPageCommand { get; }

        private async Task LoadDataAsync()
        {
            try
            {
                IsLoading = true;
                
                var url = $"/api/LMZWorkSchedule/inspection-records?pageIndex={CurrentPage}&pageSize={PageSize}";
                if (!string.IsNullOrEmpty(OrderNameFilter))
                {
                    url += $"&orderName={Uri.EscapeDataString(OrderNameFilter)}";
                }

                var response = await _apiService.GetAsync(url);
                var result = JsonConvert.DeserializeObject<InspectionRecordResponse>(response);

                if (result?.IsSuc == true && result.Data?.Data != null)
                {
                    InspectionRecords.Clear();
                    foreach (var record in result.Data.Data)
                    {
                        InspectionRecords.Add(record);
                    }

                    TotalRecords = result.Data.TotalCount;
                    TotalPages = result.Data.TotalPage;
                }
            }
            finally
            {
                IsLoading = false;
            }
        }

        private async Task SearchAsync()
        {
            CurrentPage = 1;
            await LoadDataAsync();
        }

        private async Task ResetAsync()
        {
            OrderNameFilter = string.Empty;
            CurrentPage = 1;
            await LoadDataAsync();
        }

        private async Task GoToFirstPageAsync()
        {
            CurrentPage = 1;
            await LoadDataAsync();
        }

        private async Task GoToPreviousPageAsync()
        {
            if (CurrentPage > 1)
            {
                CurrentPage--;
                await LoadDataAsync();
            }
        }

        private async Task GoToNextPageAsync()
        {
            if (CurrentPage < TotalPages)
            {
                CurrentPage++;
                await LoadDataAsync();
            }
        }

        private async Task GoToLastPageAsync()
        {
            CurrentPage = TotalPages;
            await LoadDataAsync();
        }

        private void UpdateCommandStates()
        {
            (FirstPageCommand as RelayCommand)?.RaiseCanExecuteChanged();
            (PreviousPageCommand as RelayCommand)?.RaiseCanExecuteChanged();
            (NextPageCommand as RelayCommand)?.RaiseCanExecuteChanged();
            (LastPageCommand as RelayCommand)?.RaiseCanExecuteChanged();
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    // 简单的RelayCommand实现
    public class RelayCommand : ICommand
    {
        private readonly Func<Task> _executeAsync;
        private readonly Func<bool> _canExecute;

        public RelayCommand(Func<Task> executeAsync, Func<bool> canExecute = null)
        {
            _executeAsync = executeAsync ?? throw new ArgumentNullException(nameof(executeAsync));
            _canExecute = canExecute;
        }

        public event EventHandler CanExecuteChanged;

        public bool CanExecute(object parameter)
        {
            return _canExecute?.Invoke() ?? true;
        }

        public async void Execute(object parameter)
        {
            await _executeAsync();
        }

        public void RaiseCanExecuteChanged()
        {
            CanExecuteChanged?.Invoke(this, EventArgs.Empty);
        }
    }
}